package com.pachong.frameworkdemo.common.http;

import android.util.Base64;
import android.util.Log;

import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Authorization
 * @author yanglizhe
 *
 */
public class Authorization {
	

	private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	/**
	 * 获取随机8个字母
	 * @param length
	 * @return
     */
	public static String getRandomString(int length) { 
		StringBuffer sb = new StringBuffer(); 
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			sb.append(CHARS.charAt(random.nextInt(CHARS.length()))); 
		} 
		return sb.toString(); 
	}
	
	public static String createAuthorization(TokenInfo token, String url, String method){
		if(token == null){
			return null;
		}
		String id = token.getAccessToken();  // access token
		long time = System.currentTimeMillis();  // current time in millis
		String randomStr = getRandomString(8);  // random 8 char
		String nonce = time+ ":" + randomStr;
		String string = url.replaceAll("^(http|https)://", "");
		String[] urlInfo = string.split("/", 2);
		String requestContent = String.format("%s\n%s\n%s\n%s\n",nonce, method.toUpperCase(), "/" + urlInfo[1], urlInfo[0]);
		String mac = createMac(token.getMacKey(), toCamelCase(token.getMacAlgorithm()), requestContent);
		Log.e("vivi", "  mac string == " + mac);
		return "MAC id=\"" + id + "\",nonce=\"" + nonce + "\",mac=\"" + mac + "\"";
	}
	
	public static String createMac(String macKey, String macAlgorithm, String requestContent){
		Log.e("vivi", "   mac key == " + macKey + " algorithm == " + macAlgorithm + " data == " + requestContent);
		try{
			Mac mac = Mac.getInstance(macAlgorithm);
		    byte[] secretByte = macKey.getBytes("UTF-8");
		    byte[] dataBytes = requestContent.getBytes("UTF-8");
		    SecretKey secret = new SecretKeySpec(secretByte, macAlgorithm.toUpperCase());
		    mac.init(secret);
		    byte[] doFinal = mac.doFinal(dataBytes);
		    return Base64.encodeToString(doFinal, Base64.NO_WRAP);
		}
		catch(Exception ex){
			Log.e(ex.getMessage(), ex.toString());
			return null;
		}
	}

	/**
	 * 转成骆驼命名法（Camel）
	 * @param string
	 * @return
     */
	public static String toCamelCase(String string){
		String[] arr = string.split("-");
		StringBuffer stringBuffer = new StringBuffer();
		for(String str : arr){
			stringBuffer.append(str.substring(0, 1).toUpperCase() + str.substring(1));
		}
		return stringBuffer.toString();
	}
}
